//
//  main.m
//  unionfs
//
//  Created by doug on 2009-01-02.
//
// Compile on the command line as follows:
//  gcc -o "unionfs" unionfs_Filesystem.m main.m 
//      -framework MacFUSE -framework Foundation
//
#import <sys/stat.h>
#import <Foundation/Foundation.h>
#import <MacFUSE/GMUserFileSystem.h>
#import "unionfs_Filesystem.h"

int main(int argc, char* argv[], char* envp[], char** exec_path) {
  NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
  
  NSUserDefaults *args = [NSUserDefaults standardUserDefaults];
  NSString* mountPath = [args stringForKey:@"mountPath"];
  NSString* iconPath = [args stringForKey:@"volicon"];
	
	if (!mountPath || [mountPath isEqualToString:@""]) {
		static const char  fmtstring[] = "\nUsage: %s -mountPath <path> [-volicon <path>] path1 [path2 ...] \n"
		"  -mountPath: Mount point to use.\n"
		"  path1 path2 ...: paths to be merged into]\n" 
		"Ex: %s -mountPath /Volumes/merged /users/doug/path1 /users/doug/path2\n\n";
		printf(fmtstring, argv[0],argv[0]);
		return 0;
	}
	
  //get the list of the paths into an array.
   int filesOffset = 3;

	
  if (!iconPath) {
    // We check for a volume icon embedded as our resource fork.
    char program_path[PATH_MAX] = { 0 };
    if (realpath(*exec_path, program_path)) {
      iconPath = [NSString stringWithFormat:@"%s/..namedfork/rsrc", program_path];
      struct stat stat_buf;
      memset(&stat_buf, 0, sizeof(stat_buf));
      if (stat([iconPath UTF8String], &stat_buf) != 0 || stat_buf.st_size <= 0) {
        iconPath = nil;  // We found an exec path, but the resource fork is empty.
      }
    }
  }
  else
  {
	  filesOffset += 2;
  }
  
	
	char *const *filesPtr = &argv[filesOffset];
	NSMutableArray *files = [[NSMutableArray new] init]; //hold the paths to overlay into one folder.
	
	
	const int countPaths = argc-filesOffset; //how many paths to expect once we subtract off executable name and options
	
	
	for(int count = countPaths; count--; )
	{
		NSString *stringFromMORString =
		[[NSString alloc] initWithCString:*filesPtr
								 encoding:NSMacOSRomanStringEncoding];
		
		
		[files addObject: stringFromMORString];
		filesPtr++;
	}
	

  unionfs_Filesystem* fs = 
  [[unionfs_Filesystem alloc] initWithPaths:files];
	
  GMUserFileSystem* userFS = [[GMUserFileSystem alloc] initWithDelegate:fs 
                                                           isThreadSafe:NO];
  
  NSMutableArray* options = [NSMutableArray array];
  if (iconPath != nil) {
    NSString* volArg = [NSString stringWithFormat:@"volicon=%@", iconPath];
    [options addObject:volArg];
  }
  [options addObject:@"volname=unionfs"];
  [options addObject:@"rdonly"];   
	
	
  [userFS mountAtPath:mountPath 
          withOptions:options 
     shouldForeground:YES 
      detachNewThread:NO];
  
  [userFS release];
  [fs release];
  
  [pool release];
  return 0;
}
